package net.flintx.array;

import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;

/**
 * Created by flintx on 2018/1/10.
 */
public class ThirdMaximumNumber {
    public int thirdMax(int[] nums) {
        HashSet<Integer> set = new HashSet<>();
        for (int num :
                nums) {
            set.add(num);
        }
        if (set.size() < 3) {
            return set.size() == 1? nums[0]: Math.max((int)set.toArray()[0], (int)set.toArray()[1]);
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        for (int num :
                set) {
            if (queue.size() < 3) {
                queue.add(num);
            } else if (queue.size() >= 3) {
                int e = queue.poll();
                queue.add(Math.max(e, num));
            }
        }
        int thirdNumber = queue.poll();
        return thirdNumber;
    }

    public static void main(String[] args) {
//        int[] nums = {2, 2, 3, 1};
        int[] nums = {1, 1, 2};
        System.out.println(new ThirdMaximumNumber().thirdMax(nums));
    }
}
